<template>
  <div class="max-w-6xl mx-auto p-6 min-h-screen bg-gradient-to-br from-slate-50 to-emerald-50">
    <!-- 页面标题 -->
    <div class="text-center mb-8 p-8 bg-white rounded-2xl shadow-lg">
      <h2 class="flex items-center justify-center gap-3 text-3xl font-semibold text-gray-800 mb-2">
        <n-icon class="text-4xl text-emerald-500" :component="DocumentTextIcon" />
        预备期思想汇报编辑
      </h2>
      <p class="text-gray-600">请完善预备期思想汇报记录</p>
    </div>

    <!-- 提示信息模块 -->
    <div class="mb-6 bg-gradient-to-r from-emerald-50 to-green-50 border border-emerald-200 rounded-2xl p-6 shadow-sm">
      <div class="flex items-center gap-3 mb-4">
        <n-icon class="text-2xl text-emerald-600" :component="InfoIcon" />
        <h3 class="text-lg font-semibold text-emerald-800">重要提示信息</h3>
      </div>
      <div class="space-y-2">
        <div v-for="(tip, index) in tipMessages" :key="index" class="flex items-start gap-3 text-sm text-emerald-700">
          <div class="flex-shrink-0 w-1.5 h-1.5 bg-emerald-500 rounded-full mt-2"></div>
          <span>{{ tip }}</span>
        </div>
      </div>
    </div>

    <!-- 预备期思想汇报列表卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-500" :component="DocumentTextIcon" />
            <span class="text-lg font-semibold text-gray-800">预备期思想汇报列表</span>
          </div>
          <n-button 
            type="primary" 
            @click="addReport"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增思想汇报
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!probationaryThoughtReports || probationaryThoughtReports.length === 0"
          description="暂无思想汇报记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="DocumentTextIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(report, index) in probationaryThoughtReports" :key="report.tempId || report.id || index" class="bg-emerald-50 border border-emerald-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-emerald-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="report.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="primary" 
                @click="saveReport(report, index)"
                :loading="reportSaveLoading[index]"
                :disabled="!reportChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deleteReport(report, index)"
                :loading="reportDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ report.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          <n-grid :cols="12" :x-gap="12" :y-gap="6">
            <n-gi :span="12">
              <n-form-item label="思想汇报落款时间" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="report.signatureDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择思想汇报落款时间"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import {
  NForm, NFormItem, NFormItemGi, NGrid, NDatePicker, NButton, NGi, NCard, NIcon, NEmpty
} from 'naive-ui'
import { 
  DocumentText as DocumentTextIcon,
  Add as PlusIcon,
  TrashOutline as DeleteIcon,
  InformationCircle as InfoIcon,
  Save as SaveIcon
} from '@vicons/ionicons5'
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  member: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'save-probationary-thought-report',
  'delete-probationary-thought-report'
])

// 安全处理日期字段的函数
const safeDateValue = (dateStr) => {
  if (!dateStr || dateStr === '' || dateStr === 'null' || dateStr === 'undefined') {
    return null
  }
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) {
    return null
  }
  return dateStr
}

// 列表数据
const probationaryThoughtReports = ref([])

// 原始数据副本，用于比较变化
const originalProbationaryThoughtReports = ref([])

// 变化状态
const reportChanged = ref({})

// 加载状态
const reportSaveLoading = ref({})
const reportDeleteLoading = ref({})

// 提示信息配置
const tipMessages = ref([
  '预备期党员应定期递交思想汇报，建议每季度至少一次',
  '思想汇报应真实反映个人在预备期的思想动态和学习体会',
  '汇报时间应按照实际递交日期填写',
  '建议保持思想汇报的连续性和时间间隔的合理性',
  '每份思想汇报都应有明确的落款时间'
])

// 生成唯一临时ID
const generateTempId = () => {
  return `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 配置提示信息内容的函数（预留接口）
const configureTipMessages = (messages) => {
  if (Array.isArray(messages)) {
    tipMessages.value = messages
  }
}

// 深度比较对象是否相等
const isEqual = (obj1, obj2) => {
  return JSON.stringify(obj1) === JSON.stringify(obj2)
}

// 初始化数据
const initData = () => {
  if (props.member) {
    // 初始化预备期思想汇报数据并处理日期字段
    const reportsData = (props.member.probationaryThoughtReports || []).map(report => ({
      ...report,
      signatureDate: safeDateValue(report.signatureDate)
    }))
    
    probationaryThoughtReports.value = cloneDeep(reportsData)
    
    // 保存原始数据
    originalProbationaryThoughtReports.value = cloneDeep(reportsData)
  }
}

// 监听预备期思想汇报列表变化
watch(probationaryThoughtReports, (newList) => {
  newList.forEach((item, index) => {
    const original = originalProbationaryThoughtReports.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录，检查是否有内容变化
      const emptyItem = {
        signatureDate: null
      }
      reportChanged.value[index] = !isEqual({
        signatureDate: item.signatureDate
      }, emptyItem)
    } else {
      // 现有记录，与原始数据比较
      reportChanged.value[index] = !isEqual({
        signatureDate: item.signatureDate
      }, {
        signatureDate: original.signatureDate
      })
    }
  })
}, { deep: true })

onMounted(() => {
  initData()
})

watch(() => props.member, () => {
  initData()
}, { deep: true })

// =============== 预备期思想汇报操作 ===============
const addReport = () => {
  const tempId = generateTempId()
  const newReport = {
    tempId,
    isNew: true,
    signatureDate: null
  }
  probationaryThoughtReports.value.unshift(newReport)
}

const saveReport = async (report, index) => {
  reportSaveLoading.value[index] = true
  try {
    const reportData = { ...report }
    delete reportData.tempId
    delete reportData.isNew
    
    if (report.isNew) {
      await emit('save-probationary-thought-report', reportData, -1) // -1 表示新增
    } else {
      await emit('save-probationary-thought-report', reportData, index)
    }
    
    // 保存成功后更新状态
    reportChanged.value[index] = false
    if (report.isNew) {
      report.isNew = false
    }
  } finally {
    reportSaveLoading.value[index] = false
  }
}

const deleteReport = async (report, index) => {
  if (report.isNew) {
    // 新增的记录直接移除
    probationaryThoughtReports.value.splice(index, 1)
    return
  }
  
  reportDeleteLoading.value[index] = true
  try {
    await emit('delete-probationary-thought-report', report, index)
    // 删除成功后从列表中移除
    probationaryThoughtReports.value.splice(index, 1)
  } finally {
    reportDeleteLoading.value[index] = false
  }
}

// =============== 数据更新方法（父组件调用） ===============
const updateProbationaryThoughtReports = (newList) => {
  const processedList = newList.map(report => ({
    ...report,
    signatureDate: safeDateValue(report.signatureDate)
  }))
  probationaryThoughtReports.value = cloneDeep(processedList)
  originalProbationaryThoughtReports.value = cloneDeep(processedList)
}

// 获取编辑后的数据，用于保存到后端
const getEditedData = () => {
  // 直接返回probationaryThoughtReports数组
  return probationaryThoughtReports.value;
}

defineExpose({
  configureTipMessages,
  updateProbationaryThoughtReports,
  getEditedData
})
</script>